import { Tag } from "server/models/Tag";
import { successResponse, errorResponse } from "server/utils/response";

export default defineEventHandler(async (event) => {
  try {
    const tagId = getRouterParam(event, "id");
    if (!tagId) {
      return errorResponse("参数错误", "标签ID不能为空");
    }

    // 获取标签信息
    const allTags = await Tag.getTagsWithPostCount();
    const existingTag = allTags.find((t) => t.id?.toString() === tagId);

    if (!existingTag) {
      return errorResponse("标签不存在", "指定的标签不存在");
    }

    // 检查标签下是否有文章
    if (existingTag.post_count && existingTag.post_count > 0) {
      return errorResponse("删除失败", "该标签下还有文章，无法删除");
    }

    const success = await Tag.delete(tagId);

    if (!success) {
      return errorResponse("删除失败", "标签删除失败");
    }

    return successResponse(null, "标签删除成功");
  } catch (error) {
    console.error("删除标签失败:", error);
    return errorResponse(
      "删除标签失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});
